import logging

from blueapps.patch.settings_open_saas import default
from celery import task, shared_task
from django.db import transaction
from django.db.models import F
from django_celery_results.managers import transaction_retry

from bk_framework_app.models import ApiRequestCount

logger = logging.getLogger(__name__)


@shared_task(bind=True, max_retries=3)
def record_api_request(api_name, api_category):
    try:
        with transaction.atomic():
            obj, created = ApiRequestCount.objects.select_for_update().get_or_create(
                api_name=api_name,
                api_category=api_category,
                defaults={'api_count': 0}
            )
            obj.api_count = F('api_count') + 1
            obj.save(update_fields=['api_count'])
            print("成功")
    except Exception as e:
        logger.exception(e)

